package com.orange.wwwapi.service.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orange.core.mapper.user.UserCarMapper;
import com.orange.core.pojo.PageReqDto;
import com.orange.core.pojo.entity.user.User;
import com.orange.core.pojo.entity.user.UserCar;
import com.orange.core.pojo.req.car.UserCarPageReq;
import com.orange.core.service.user.UserService;
import com.orange.core.util.PrincipalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class UserCarService extends ServiceImpl<UserCarMapper, UserCar> {

    private final UserService userService;

    public Page<UserCar> page(PageReqDto<UserCarPageReq> req) {
        if (req.getCondition() == null) {
            req.setCondition(new UserCarPageReq());
        }
        UserCarPageReq condition = req.getCondition();
        if (StrUtil.isNotEmpty(condition.getUserNo())) {
            User user = userService.lambdaQuery()
                    .eq(User::getUserNo, condition.getUserNo())
                    .one();
            if (user == null) {
                return new Page<>(req.getPage(), 0, 0);
            } else {
                condition.setUserId(user.getId());
            }
        }

        Page<UserCar> page = this.lambdaQuery()
                .eq(condition.getUserId() != null, UserCar::getUserId, condition.getUserId())
                .eq(condition.getPlateNo() != null, UserCar::getPlateNo, condition.getPlateNo())
                .orderByDesc(UserCar::getId)
                .page(req.toPage());
        List<UserCar> records = page.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            List<Integer> userIds = records.stream().map(UserCar::getUserId).toList();
            Map<Integer, User> userMap = userService.lambdaQuery()
                    .in(User::getId, userIds)
                    .list().stream().collect(Collectors.toMap(User::getId, Function.identity()));
            for (UserCar record : records) {
                record.setUserNo(userMap.get(record.getUserId()).getUserNo());
                record.setUserNickname(userMap.get(record.getUserId()).getNickname());
            }
        }
        return page;
    }

    public boolean save(UserCar userCar) {
        Optional<UserCar> opt = this.lambdaQuery()
                .eq(UserCar::getUserId, PrincipalUtil.getId())
                .eq(UserCar::getPlateNo, userCar.getPlateNo())
                .oneOpt();
        if (opt.isPresent()) {
            return true;
        }

        userCar.setUserId(PrincipalUtil.getId());
        processPlateNo(userCar);
        return super.save(userCar);
    }

    public boolean update(UserCar userCar) {
        processPlateNo(userCar);
        return super.updateById(userCar);
    }

    public boolean unbind(int id) {
        Assert.isTrue(this.lambdaQuery()
                .eq(UserCar::getUserId, PrincipalUtil.getId())
                .exists(), "车辆不存在");
        return this.removeById(id);
    }

    private void processPlateNo(UserCar userCar) {
        userCar.setPlatePrefix(userCar.getPlateNo().substring(0, 2));
        userCar.setPlateSuffix(userCar.getPlateNo().substring(2));
    }
}
